import unittest
from kea2 import precondition, prob, Hook
from kea2.hypiumUtils import get_hierarchy, get_node, get_bounds, traverse_uiTree
from hypium import BY, UiDriver

class RedNote(unittest.TestCase):
    d: "UiDriver"

    @classmethod
    def setUpClass(cls):
        cls.d = UiDriver.connect(
            device_sn="33Z0224620051970",
            connector="hdc"
        )

    @prob(0.8)
    @precondition(
        lambda self: (
            self.d.find_component(BY.id("rich_editor_social_use")) and
            len(self.d.find_component(BY.id("rich_editor_social_use")).getText()) > 0
        )
    )
    def test_send_button_should_exist_when_inputbox_has_text(self):
        assert self.d.find_component(BY.text("发送"))

    @prob(0.8)
    @precondition(
        lambda self: (
            self.d.find_component(BY.type("RichEditor")) and
            len(self.d.find_component(BY.type("RichEditor")).getText() == 0)
        )
    )
    def test_input_text(self):
        import uuid
        input_text = str(uuid.uuid4())
        self.d.input_text(BY.type("RichEditor"),input_text)
        assert self.d.find_component(BY.text(input_text))


class PerformanceHook(Hook):
    
    def before(self):
        print("Hook01 Before monkey execution")
        self.traceRecorder.start()

    def after(self):
        self.traceRecorder.end()
        print("Hook01 After monkey execution")
        if (switch_time := self.traceRecorder.get_duration("H:ABILITY_OR_PAGE_SWITCH")):
            print(f"Checking Hook01 switch time: {switch_time} seconds")
            assert switch_time < 0.5, f"Switch time is too long: {switch_time} seconds"
            print("Hook01 passed")

class UXHook(Hook):
    
    def before(self):
        print("UXHook Before monkey execution")

    def after(self):
        h = get_hierarchy()
        n = get_node(h, lambda node: node.get("bundleName", "") == "com.ohos.sceneboard")
        if n:
            scene_bound = get_bounds(n)
            
            def not_overlap_scene(node_attrs):
                # if the node has no identifying attributes (meaningless), skip it
                if not any([
                    node_attrs.get("id", "") != "",
                    node_attrs.get("key", "") != "",
                    node_attrs.get("text", "") != "",
                    node_attrs.get("description", "") != ""
                ]):
                    return False
                
                bounds = get_bounds(node_attrs)
                horizontal_overlap = scene_bound[0] < bounds[2] and bounds[0] < scene_bound[2]
                vertical_overlap = scene_bound[1] < bounds[3] and bounds[1] < scene_bound[3]
                return horizontal_overlap and vertical_overlap

            assert not traverse_uiTree(h, not_overlap_scene), "Overlap with scene detected"


if __name__ == "__main__":
    d = UiDriver.connect(
        device_sn = "23E0224307001843",
        connector="hdc"
    )
